var map;
var markerBegin;
var markerTarget;
var markerClickBegin, markerClickEnd;
var myCenter=new google.maps.LatLng(10.77201024033738, 106.65770083665848);

// ========================================================================
var directionsService = new google.maps.DirectionsService();
var timeout = 200;

var directionsServiceshow = new google.maps.DirectionsService();

// ========================================================================
var pathGetStationNear = "getNearPoint.php"; // // Get station near -- function clickGetStation()
var afterSort = [];
// ========================================================================

function initialize()
{
	var mapProp = {
		center:myCenter,
		zoom:13,
		mapTypeId:google.maps.MapTypeId.ROADMAP
	};
	map=new google.maps.Map(document.getElementById("right"),mapProp);


	google.maps.event.addListener(map, 'click', function( event ){
		clickGetStation(event.latLng.lat(), event.latLng.lng());
	});
}

function addMarker(position) // ok
{
	var marker=new google.maps.Marker({
		position:position,
	});
	marker.setMap(map);
}

function addMarkerBeginAndTarget(order) // ok
{
	switch(order)
	{
		case 'begin':
			if(markerBegin != null)
			{
				google.maps.event.clearListeners(markerBegin, 'click');
	    		markerBegin.setMap(null);
			}
	    	var getDataBegin = ($('#begin').val()).split('bkcse');
	    	var position = new google.maps.LatLng(parseFloat(getDataBegin[1]), parseFloat(getDataBegin[2]));
	    	markerBegin=new google.maps.Marker({
				position:position,
				icon : 'img/marker/green-dot.png',
				animation:google.maps.Animation.BOUNCE
			});
			markerBegin.setMap(map);
			map.setCenter(position);
			// click show information =======================================
			var infowindow = new google.maps.InfoWindow({
				content:"Begin"
			});
			google.maps.event.addListener(markerBegin, 'click', function() {
				infowindow.open(map,markerBegin);
			});
			// ==============================================================
		break;
		case 'target':
			if(markerTarget != null)
			{
				google.maps.event.clearListeners(markerTarget, 'click');
	    		markerTarget.setMap(null);
			}
	    	var getDataTarget = ($('#target').val()).split('bkcse');
	    	var position = new google.maps.LatLng(parseFloat(getDataTarget[1]), parseFloat(getDataTarget[2]));
	    	markerTarget=new google.maps.Marker({
				position:position,
				icon : 'img/marker/red-dot.png',
				animation:google.maps.Animation.BOUNCE
			});
			markerTarget.setMap(map);
			map.setCenter(position);
			// click show information =======================================
			var infowindow = new google.maps.InfoWindow({
				content:"Target"
			});
			google.maps.event.addListener(markerTarget, 'click', function() {
				infowindow.open(map,markerTarget);
			});
			// ==============================================================
		break;
	}
}

// ============================================================================================================
function travelNode(address, route)  {
	var routeS = 0;
    // addMarker(new google.maps.LatLng(address[0].lat, address[0].lon));
    for (var ix=0; ix < address.length; ix++) {
    	var color = '#F75C54';
    	var dataTemp = address[ix];
    	var routeTemp = dataTemp[2];

    	//console.log(routeTemp);

    	var request;

    	if(parseInt(routeTemp) == 0)
    	{
    		color = '#0F0'; // F75C54 // #0F0 // #06F
    		request = {
	            origin      : new google.maps.LatLng(dataTemp[0].lat, dataTemp[0].lon),
	            destination : new google.maps.LatLng(dataTemp[1].lat, dataTemp[1].lon),
	            travelMode  : google.maps.DirectionsTravelMode.WALKING
	        };
    	}
    	else if(route != null && routeTemp == route){
    		color = '#000000'; // F75C54 // #0F0 // #06F
    		request = {
	            origin      : new google.maps.LatLng(dataTemp[0].lat, dataTemp[0].lon),
	            destination : new google.maps.LatLng(dataTemp[1].lat, dataTemp[1].lon),
	            travelMode  : google.maps.DirectionsTravelMode.WALKING
	        };
    	}
    	else
    	{
    		request = {
	            origin      : new google.maps.LatLng(dataTemp[0].lat, dataTemp[0].lon),
	            destination : new google.maps.LatLng(dataTemp[1].lat, dataTemp[1].lon),
	            travelMode  : google.maps.DirectionsTravelMode.DRIVING
	        };
    	}

        if(routeS != routeTemp)
        {
          if (ix > 0) {
            addMarker(new google.maps.LatLng(dataTemp[0].lat, dataTemp[0].lon));
          }
        	routeS = routeTemp;
        }
        drawRoute(request, color);
    }
    //console.log(address);
}

// show route hightlight =================================================================
function travelNodeRoute(address, route){
	var routeS = 0;
    for (var ix=0; ix < address.length; ix++) {
    	var color = '#000000';
    	var dataTemp = address[ix];
    	var routeTemp = dataTemp[2];
    	if(route == routeTemp){
    		request = {
	            origin      : new google.maps.LatLng(dataTemp[0].lat, dataTemp[0].lon),
	            destination : new google.maps.LatLng(dataTemp[1].lat, dataTemp[1].lon),
	            travelMode  : google.maps.DirectionsTravelMode.DRIVING
	        };

	        drawRoute(request, color);
    	}

    	if(routeS != routeTemp && ix > 0)
        {
        	routeS = routeTemp;
        }

    }
}

function addMarker(POSLatlng){
	var marker = new google.maps.Marker({
		position: POSLatlng,
		map: map,
		icon : 'img/marker/yellow-dot.png',
	});
}

function drawRoute(request,color) {
    directionsService.route(request, function(response, status) {
         if (status == google.maps.DirectionsStatus.OK)
         {
            var polylineOptionsActual = {
                strokeColor  :color,
                strokeOpacity: 0.7,
                strokeWeight : 5
			};
            var directionsRenderer = new google.maps.DirectionsRenderer();
            directionsRenderer.setMap(map);
            directionsRenderer.setOptions( { polylineOptions: polylineOptionsActual, suppressMarkers: true} );
            directionsRenderer.setDirections(response);
        }
        else
        {
            if (status == 'OVER_QUERY_LIMIT')
            {
                setTimeout(function() { drawRoute(request, color); }, (timeout));
            }
        }
    });
}


// Get station near -- function clickGetStation()

function clickGetStation(lat, lon){

	$.ajax({
		type: "GET",
		//datatype : "application/json",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		url: pathGetStationNear,
		data: { lat_click: lat, lon_click: lon }
	})
	.done(function( msg ) {
		calDistance(lat, lon, JSON.parse(msg));
	});
	$("#dialog").dialog("open");
}

function calDistance(lat, lon, listpoints){
	var arrDistances = [];
	for(var i = 0; i < listpoints.length; i++){
		var listpoint = listpoints[i];
		var calDis = Math.abs(lat - listpoint['lat']) + Math.abs(lon - listpoint['lon']);
		var itemArrDistance = {id: listpoint['id'], distance: calDis, lat:listpoint['lat'], lon:listpoint['lon'], name:listpoint['name']};
		arrDistances.push(itemArrDistance);
	}
	// sort
	var count = 0;
	var flag = 0;
	afterSort = [];
	while(true){
		if(count == arrDistances.length - 1){
			var idMin = 0;	idMin = arrDistances[flag].id;
			var disMin = 0; disMin = arrDistances[flag].distance;
			var latMin = 0; latMin = arrDistances[flag].lat;
			var lonMin = 0; lonMin = arrDistances[flag].lon;
			var nameMin = 0; nameMin = arrDistances[flag].name;

			var itemArraySort = {id:idMin, distance:disMin, lat:latMin, lon:lonMin, name:nameMin};
			afterSort.push(itemArraySort);
			arrDistances[flag].distance = 99.333;
			count = 0;	flag = 0;
		}
		else {
			if(parseFloat(arrDistances[count].distance) >= parseFloat(arrDistances[count+1].distance) &&
				parseFloat(arrDistances[flag].distance) >= parseFloat(arrDistances[count+1].distance)){
				flag = count + 1;
			}
		}
		if(afterSort.length == arrDistances.length){
			break;
		}
		count = count + 1;
	}
	// add data
	var stringshow = '';
	for(var i = 0; i < afterSort.length; i++){
		var label = '<label for="' + afterSort[i].id + '">' + afterSort[i].name + '</label><br><hr>';
		var radiobutton = '<input class="idstation" type="radio" name="sex" value="' + afterSort[i].id + '">';
		stringshow = stringshow + radiobutton + label;
		if(i == 3){
			break;
		}
	}
	$("#listStation").html(stringshow);
}

function diemdi(){
	// get value radio button checked
	var ids_selected = '';
	if($("input[type='radio'].idstation").is(':checked')) {
	    ids_selected = $("input[type='radio'].idstation:checked").val();
	}
	var infosChosen = infoChose(ids_selected); //object station
	var key = infosChosen["id"] + "bkcse" + infosChosen["lat"] + "bkcse" + infosChosen["lon"];
	$("#begin").val(key);
	addMarkerBeginAndTarget('begin');
	$("#dialog").dialog("close");
}

function diemden(){
	// get value radio button checked
	var ide_selected = '';
	if($("input[type='radio'].idstation").is(':checked')) {
	    ide_selected = $("input[type='radio'].idstation:checked").val();
	}
	var infoeChosen = infoChose(ide_selected);
	var key = infoeChosen["id"] + "bkcse" + infoeChosen["lat"] + "bkcse" + infoeChosen["lon"];
	$("#target").val(key);
	addMarkerBeginAndTarget('target');
	$("#dialog").dialog("close");
}

function infoChose(id){
	for(var i = 0; i < afterSort.length; i++){
		if(id == afterSort[i].id){
			return afterSort[i];
		}
	}
}

$(document).ready(function() {

	$("#dialog").dialog({
		autoOpen: false
	});

	$("#diemdi").on("click", function() {
		diemdi();
	});

	$("#diemden").on("click", function() {
		diemden();
	});
});

// ============================================================================================================

google.maps.event.addDomListener(window, 'load', initialize);
